// 前端分页
import { ref, getCurrentInstance } from 'vue'

export default function () {
    const { proxy }: any = getCurrentInstance();

    const originalData = ref([]); // 原始数据
    const tableData = ref([]); // 处理后显示的数据
    const filterData = ref([]) // 过滤条件后的数据

    const searchData = ref<any>({}); // 过滤条件

    const pageModel = ref({
        num: 1,
        size: 10,
        total: 0,
    });

    /**
     * 初始列表
     * @param data 
     * @param search 
     * @returns 
     */
    const initTable = (data: any, search: any = {}) => {
        originalData.value = data;
        searchData.value = search;
        tableData.value = [];
        filterSearch();
        getTableData();
        return tableData.value;
    }

    const getTableData = () => {
        pageModel.value.total = filterData.value.length;
        const start = (pageModel.value.num - 1) * pageModel.value.size;
        const end = (start + pageModel.value.size) > pageModel.value.total ? pageModel.value.total : (start + pageModel.value.size)
        for (let i = start; i < end; i++) {
            tableData.value.push(filterData.value[i])
        }
    }

    /**
     * 过滤条件
     * @returns 
     */
    const filterSearch = () => {
        const data = originalData.value.filter((item: any) => {
            let flag = true
            for (let i in searchData.value) {
                if (String(item[i]).indexOf(searchData.value[i]) === -1) {
                    flag = false
                }
            }
            if (flag) {
                return item
            }
        })
        filterData.value = data || [];
    }

    const jumpFirstPage = () => {
        pageModel.value.num = 1;
        getTableData()
    }

    const jumpLastPage = () => {
        pageModel.value.num = 1;
        getTableData()
    }

    // 暴露出去
    return {
        pageModel,
        initTable,
        jumpFirstPage,
    };
}
